﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using CDStore3Tiers;

namespace CuaHangDiaNhac
{
    public partial class frmChiTietHoaDon : DevComponents.DotNetBar.Office2007Form
    {
        private StoreCDDataContext dt;
        decimal tiendu = 0, datcoc = 0, tongtien = 0, TienNhan = 0;
        XuLyDatHang xldh = new XuLyDatHang();
        private int mahoadon = 0;
        log4net.ILog log = log4net.LogManager.GetLogger("Chi tiết hóa đơn");


        public frmChiTietHoaDon(int maso)
        {
            mahoadon = maso;
            InitializeComponent();
            dt = new StoreCDDataContext();
            dt.Connection.ConnectionString = getConfig.getConnection();
            var hd = dt.HoaDonBan_SelectByID(maso).First();
            DataGridViewTextBoxColumn coMaSK = new DataGridViewTextBoxColumn();
            coMaSK.DataPropertyName = "MaSK";
            coMaSK.Visible = false;
            DataGridViewTextBoxColumn coTenSK = new DataGridViewTextBoxColumn();
            coMaSK.DataPropertyName = "TenSK";
            coMaSK.Visible = false;
            if (hd != null)
            {
                txtMHD.Text = hd.MaHDBH.ToString();
                txtNDHD.Text = hd.NoiDungHD;
                List<vwChitietHD1> ct = (from ctiet in dt.vwChitietHD1s
                                         where ctiet.MaHDBH == maso
                                         select ctiet).ToList<vwChitietHD1>();
                int madh = ConvertType.ToInt(ct[0].DatHang);
                datcoc = xldh.LayDatCoc_Ma(madh);

                dgrChiTietHoaDon.AutoGenerateColumns = false;
                dgrChiTietHoaDon.DataSource = ct;
            }
            try
            {
                for (int i = 0; i < dgrChiTietHoaDon.Rows.Count; i++)
                {
                    decimal thanhtien = ConvertType.ToDecimal(dgrChiTietHoaDon.Rows[i].Cells["ThanhTien"].Value);
                    tongtien += thanhtien;
                }
                tiendu = TienNhan - tongtien - datcoc;
                lblTong.Text = Convert.ToInt32(tongtien).ToString();
                txtDatCoc.Text = (datcoc).ToString();
            }
            catch (Exception) { }
        }

        public void lockLogin()
        {
            string id = frmLogin.id;
            XLPhanQuyen phanquyen = new XLPhanQuyen();
            List<TaiKhoanChucNang> tkcn = new List<TaiKhoanChucNang>();
            tkcn = phanquyen.TKChucNang(frmLogin.id);


            if (phanquyen.CoQuyen(id, 705))
            {
                btnXoadt.Enabled = true;
            }
            if (phanquyen.CoQuyen(id, 706))
            {
                btnLuuCT.Enabled = true;
            }
        }

        public void closeall()
        {
            btnXoadt.Enabled = false;
            btnLuuCT.Enabled = false;
        }



        //        public frmChiTietHoaDon(int maso)
        //        {
        //            mahoadon = maso;
        //            InitializeComponent();
        //            dt = new StoreCDDataContext();
        //            dt.Connection.ConnectionString = getConfig.getConnection();
        //            var hd = dt.HoaDonBan_SelectByID(maso).First();
        //            DataGridViewTextBoxColumn coMaSK = new DataGridViewTextBoxColumn();
        //            coMaSK.DataPropertyName = "MaSK";
        //            coMaSK.Visible = false;
        //            DataGridViewTextBoxColumn coTenSK = new DataGridViewTextBoxColumn();
        //            coMaSK.DataPropertyName = "TenSK";
        //            coMaSK.Visible = false;
        //            decimal datcoc = 0;
        //            if (hd != null)
        //            {
        //                txtMHD.Text = hd.MaHDBH.ToString();
        //                txtNDHD.Text = hd.NoiDungHD;
        //                List<vwChitietHD1> ct = (from ctiet in dt.vwChitietHD1s
        //                                         where ctiet.MaHDBH == maso
        //                                         select ctiet).ToList<vwChitietHD1>();
        //                int madh = ConvertType.ToInt(ct[1].DatHang);
        //                datcoc = xldh.LayDatCoc_Ma(madh);
        //
        //                dgrChiTietHoaDon.AutoGenerateColumns = false;
        //                dgrChiTietHoaDon.DataSource = ct;
        //            }
        //            try
        //            {
        //
        //                decimal tongtien = 0;
        //                for (int i = 0; i < dgrChiTietHoaDon.Rows.Count; i++)
        //                {
        //                    decimal thanhtien = ConvertType.ToDecimal(dgrChiTietHoaDon.Rows[i].Cells["ThanhTien"].Value);
        //                    tongtien += thanhtien;
        //                }
        //                lblTong.Text = Convert.ToInt32(tongtien).ToString();
        //                txtDatCoc.Text = (datcoc).ToString();
        //            }
        //            catch (Exception) { }
        //
        //        }
        private string Tien(int soTien)
        {
            return String.Format("{0:0,0}", soTien);
        }
        public void Getdata(int maso)
        {
            dt = new StoreCDDataContext();
            dt.Connection.ConnectionString = getConfig.getConnection();
            var hd = dt.HoaDonBan_SelectByID(maso).First();
            if (hd != null)
            {
                decimal tongtien = 0;
                lblTong.Text = "0";
                txtMHD.Text = hd.MaHDBH.ToString();
                txtNDHD.Text = hd.NoiDungHD;
                List<vwChitietHD1> ct = XuLyChiTietHoaDon.LayDsChiTietHoaDon_MaHD(maso);
                BindingSource bds = new BindingSource();
                bds.DataSource = ct;
                bindingNavigatorEx1.BindingSource = bds;
                dgrChiTietHoaDon.DataSource = bds;
                //dgrChiTietHoaDon.DataSource = ct;
                try
                {
                    for (int i = 0; i < dgrChiTietHoaDon.Rows.Count; i++)
                    {
                        decimal thanhtien = ConvertType.ToDecimal(dgrChiTietHoaDon.Rows[i].Cells["ThanhTien"].Value);
                        tongtien += thanhtien;
                    }
                    lblTong.Text = Tien(Convert.ToInt32(tongtien));
                }
                catch (Exception) { }
            }
        }

        private void frmChiTietHoaDon_Load(object sender, EventArgs e)
        {
            closeall();
            lockLogin();

            dt = new StoreCDDataContext();
            dt.Connection.ConnectionString = getConfig.getConnection();
            Getdata(mahoadon);
            log.Info(frmLogin.id + ": đã load lên form chi tiết hóa đơn");
        }

        //bool TonTai(int s)
        //{
        //    return (from d in dt.HoaDonBans
        //            where d.MaHDBH == s
        //            select d).Count() > 0;
        //}
        int soluongdia(int a)
        {
            dt = new StoreCDDataContext();
            dt.Connection.ConnectionString = getConfig.getConnection();
            DiaNhac l = XuLyDiaNhac.LayDia_Ma(a);
            return l.SoLuongDia;
        }
        public void UpdateSoLuong()
        {
            dt = new StoreCDDataContext();
            dt.Connection.ConnectionString = getConfig.getConnection();
            for (int i = 0; i < dgrChiTietHoaDon.Rows.Count; i++)
            {
                DataGridViewRow r = dgrChiTietHoaDon.Rows[i];
                int ma = Convert.ToInt32(r.Cells["MaDia"].Value);
                int soluongmua = ConvertType.ToInt(r.Cells["SoLuong"].Value);
                string tendia = r.Cells["TenDia"].Value.ToString();
                int soluong = soluongdia(ma);
                int sl = soluong - soluongmua;
                dt.DiaNhac_UpdateSoLuong(ma, sl);
                dt.SubmitChanges();
                log.Info(frmLogin.id + ": đã cập nhật lại số lượng của đĩa nhạc " + tendia + " trong hóa đơn mã số [" + mahoadon + "]");
            }
        }
        private void btnXoadt_Click(object sender, EventArgs e)
        {

            int mahdbanhang = Convert.ToInt32(dgrChiTietHoaDon.SelectedRows[0].Cells["MaHDBH"].Value);
           
            DialogResult accept = DevComponents.DotNetBar.MessageBoxEx.Show("Ban co muon xoa chi tiet hoa don đã chọn ? ", "Thông báo", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
            if (accept == DialogResult.Yes)
            {
                for (int i = 0; i < dgrChiTietHoaDon.SelectedRows.Count; i++)
                {
                    // DataGridViewRow r = dgrChiTietHoaDon.SelectedRows[i];
                    int madia = ConvertType.ToInt(dgrChiTietHoaDon.SelectedRows[i].Cells["MaDia"].Value);
                    int maChiTiet = Convert.ToInt32(dgrChiTietHoaDon.SelectedRows[i].Cells["MaCTBH"].Value.ToString());
                    int slDia_HoaDon = XuLyDiaNhac.LaySoLuong_MaCTHD(maChiTiet);
                    int solluongdia = XuLyDiaNhac.LaySoLuong_Ma(madia);
                    int sl = solluongdia + slDia_HoaDon;
                    XuLyDiaNhac.CapNhatSoLuong(madia, sl);
                    XuLyChiTietHoaDon.XoaChiTietHoaDon(maChiTiet, mahdbanhang);

                }
                MessageBox.Show("Xoa Thanh Cong Đĩa Nhạc được chọn.");
            }

            else { ;}

            Getdata(mahdbanhang);
            XuLyHoaDon.UpdateTTHoaDon(mahdbanhang, txtNDHD.Text, dttNgay.Value);
        }
        private void btnHuyBo_Click(object sender, EventArgs e)
        {
            dt = new StoreCDDataContext();
            dt.Connection.ConnectionString = getConfig.getConnection();
            int ma = ConvertType.ToInt(txtMHD.Text);
            Getdata(ma);
        }

        private void btnLuuCT_Click(object sender, EventArgs e)
        {
            dt = new StoreCDDataContext();
            dt.Connection.ConnectionString = getConfig.getConnection();
            int j = ConvertType.ToInt(txtMHD.Text);
            Getdata(j);
            XuLyHoaDon.UpdateTTHoaDon(j, txtNDHD.Text, dttNgay.Value);

        }
        private void dgrChiTietHoaDon_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            dt = new StoreCDDataContext();
            dt.Connection.ConnectionString = getConfig.getConnection();
            int j = ConvertType.ToInt(txtMHD.Text);
            DataGridViewRow r = dgrChiTietHoaDon.Rows[e.RowIndex];
            int ma = ConvertType.ToInt(r.Cells["MaDia"].Value);
            int mact = ConvertType.ToInt(r.Cells["MaCTBH"].Value);
            int madia = ConvertType.ToInt(r.Cells["MaDia"].Value);
            int sl = ConvertType.ToInt(r.Cells["SoLuong"].Value);
            decimal dongia = ConvertType.ToDecimal(r.Cells["DonGia"].Value);
            int sukien = ConvertType.ToInt(r.Cells["SuKien"].Value);
            int dathang = ConvertType.ToInt(r.Cells["DatHang"].Value);
            decimal thanhtien = dongia * sl;


            if (dathang != 0)
            {
                XuLyChiTietHoaDon.CapNhatChiTietHD_DatHang(mact, j, madia, sl, dongia, sukien, dathang, thanhtien);
                dt.SubmitChanges();
            }
            else
            {
                XuLyChiTietHoaDon.CapNhatChiTietHD(mact, j, madia, sl, dongia, sukien, thanhtien);
                dt.SubmitChanges();
            }

            int slHienTai = XuLyDiaNhac.LaySoLuong_Ma(ma);
            int slCapNhat = ConvertType.ToInt(r.Cells["SoLuong"].Value);
            int DoLech = XuLyDiaNhac.Dochenhlech(slCapNhat, ConvertType.ToInt(r.Cells["MaCTBH"].Value));
            if (slCapNhat <= 0)
                MessageBox.Show("so luong cap nhat phai lon hon 0");
            else
            {
                if (DoLech > 0)
                {
                    if (slHienTai < DoLech)
                        MessageBox.Show("so luong" + r.Cells["coTenDia"].Value.ToString() + " con lai khong du de cap nhat.");
                    else
                    {
                        sl = slHienTai - DoLech;
                        dt.DiaNhac_UpdateSoLuong(ma, sl);
                    }
                }
                else
                {
                    sl = slHienTai + DoLech;
                    XuLyDiaNhac.CapNhatSoLuong(ma, sl);
                }
            }
        }
        private void txtTienNhan_TextChanged(object sender, EventArgs e)
        {
            decimal TienNhan = ConvertType.ToDecimal(txtTienNhan.Text);
            decimal tienthua = TienNhan - tongtien - datcoc;
            txtTienThua.Text = ConvertType.ToString(tienthua);
        }
        private void btnLoadDanhSach_Click(object sender, EventArgs e)
        {
            int j = ConvertType.ToInt(txtMHD.Text);
            Getdata(j);
            log.Info(frmLogin.id + ": đã làm mới danh sách hóa đơn mã số [" + mahoadon + "]");
        }

        private void lblTong_TextChanged(object sender, EventArgs e)
        {
            decimal TienNhan = ConvertType.ToDecimal(txtTienNhan.Text);
            decimal tienthua = TienNhan - tongtien - datcoc;
            txtTienThua.Text = ConvertType.ToString(tienthua);
        }

        public void LayTongTien()
        {
            tongtien = 0;
            for (int i = 0; i < dgrChiTietHoaDon.Rows.Count; i++)
            {
                decimal thanhtien = ConvertType.ToDecimal(dgrChiTietHoaDon.Rows[i].Cells["ThanhTien"].Value);
                tongtien += thanhtien;
            }
            lblTong.Text = Tien(Convert.ToInt32(tongtien));
        }

        private void lbPre_Click(object sender, EventArgs e)
        {

        }

        private void txtPage_Leave(object sender, EventArgs e)
        {

        }

        private void txtPage_KeyDown(object sender, KeyEventArgs e)
        {

        }

        private void lbNext_Click(object sender, EventArgs e)
        {

        }

        private void lbDnext_Click(object sender, EventArgs e)
        {

        }

        private void btXoa_Click(object sender, EventArgs e)
        {
            MessageBox.Show("ban co muon xoa nhung hoa don da chon.");
        }
    }
}
